package com.ego.goodsweb.listener;

import com.ego.goodsweb.service.GoodsWebService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;


@Component
public class ItemListener {

    @Resource
    private GoodsWebService goodsWebService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "ego.create.html.queue", durable = "true"),
            exchange = @Exchange(
                    value = "ego.item.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
            key = {"item.insert", "item.update"}))
    public void createStaticHtml(Long spuId, Message message, Channel channel) throws IOException {
        try {
            Map<String, Object> modelMap = goodsWebService.loadModel(spuId);
            goodsWebService.createStaticHtml(spuId, modelMap);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (Exception e) {
            e.printStackTrace();
            //写日志
            //发送到死信队列
            //拒绝消费，但是不重新入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }

}
